package com.vipboot.platform.system.crud.service;

import cn.hutool.core.util.ObjectUtil;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.vipboot.framework.core.constant.Const;
import com.vipboot.framework.core.constant.TenantConst;
import com.vipboot.framework.satoken.helper.LoginHelper;
import com.vipboot.platform.system.crud.dao.SysMenuDao;
import com.vipboot.platform.system.crud.dao.SysRoleDao;
import com.vipboot.platform.system.domain.entity.*;
import com.vipboot.platform.system.domain.vo.SysRoleVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@RequiredArgsConstructor
@Service
public class PermissionService {

    private final SysRoleDao sysRoleDao;
    private final SysMenuDao sysMenuDao;

    /**
     * 获取角色数据权限
     *
     * @param userId 用户id
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(Long userId) {

        Set<String> roles = new HashSet<>();
        // 管理员拥有所有权限
        if (LoginHelper.isSuperAdmin(userId)) {
            roles.add(TenantConst.SuperAdminRoleKey);
        } else {
            roles.addAll(this.listRolePermissionByUserId(userId));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param userId 用户id
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(Long userId) {
        Set<String> perms = new HashSet<>();
        // 管理员拥有所有权限
        if (LoginHelper.isSuperAdmin(userId)) {
//            perms.add("*:*:*");
            perms.add("*:*");
        } else {
            perms.addAll(this.listMenuPermsByUserId(userId));
        }
        return perms;
    }


    /**
     * 根据用户ID查询角色权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    private Set<String> listRolePermissionByUserId(Long userId) {
        MPJLambdaWrapper<SysRole> queryWrapper = JoinWrappers.lambda();
        queryWrapper.select(SysRole::getRoleKey)
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRole::getRoleId)
                .leftJoin(SysUser.class, SysUser::getUserId, SysUserRole::getUserId)
                .eq(SysUserRole::getUserId, userId);

        List<SysRoleVo> perms = sysRoleDao.selectJoinList(SysRoleVo.class, queryWrapper);
        Set<String> permsSet = new HashSet<>();
        for (SysRoleVo perm : perms) {
            if (ObjectUtil.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }


    /**
     * 根据用户ID查询菜单权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    private Set<String> listMenuPermsByUserId(Long userId) {
        /*select distinct m.perms
        from sys_menu m
        left join sys_role_menu rm on m.menu_id = rm.menu_id
        left join sys_user_role ur on rm.role_id = ur.role_id
        left join sys_role r on r.role_id = ur.role_id
        where m.status = '0' and r.status = '0' and ur.user_id = #{userId}*/
        MPJLambdaWrapper<SysMenu> queryWrapper = JoinWrappers.lambda();
        queryWrapper.select(SysMenu::getPerms)
                .leftJoin(SysRoleMenu.class, SysRoleMenu::getMenuId, SysMenu::getMenuId)
                .leftJoin(SysUserRole.class, SysUserRole::getRoleId, SysRoleMenu::getRoleId)
                .leftJoin(SysRole.class, SysRole::getRoleId, SysUserRole::getRoleId)
                .eq(SysUserRole::getUserId, userId)
                .eq(SysRole::getStatus, Const.StatusNormal)
                .eq(SysMenu::getStatus, Const.StatusNormal);

        List<String> perms = sysMenuDao.selectJoinList(String.class, queryWrapper);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (ObjectUtil.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

}

